// File Name: rs485_ctrl.c
// Author: kukukukuku~
// Date: 2024-07-16

#include "./User/RS485/inc/rs485_ctrl.h"

//RS485串口支持的波特率列表
const uint32_t rs485UsartBaudRateList[10] = 
{
    9600,
    19200,
    38400,
    57600,
    74800,
    115200,
    230400,
    460800,
    500000,
    576000,
};

uint32_t rs485UsartBaudRate;    //RS485串口波特率
uint32_t rs485UsartBaudRateNew; //RS485新串口波特率

uint16_t rs485ActiveInterval;   //RS485主动模式发送时间间隔

uint8_t rs485UsartTxBuffer[RS485_USART_TX_BUFFER_LEN];  //RS485串口发送缓冲区
uint8_t rs485UsartRxBuffer[RS485_USART_RX_BUFFER_LEN];  //RS485串口接收缓冲区
uint8_t rs485UsartRxIndex;      //RS485串口接收下标
uint8_t rs485UsartRxFinishFlag; //RS485串口接收完成标志

uint8_t rs485Mode;  //RS485工作模式
uint8_t rs485Id;    //RS485设备编号

uint8_t rs485SaveFlag;  //RS485接收到保存命令标志
uint8_t rs485RebootFlag;    //RS485接收到重启命令标志
uint8_t rs485ResetFlag;     //RS485接收到恢复出厂设置命令标志

/**
 * @brief   RS485初始化
 * @param   None
 * @retval  None
 * @note    静态函数
*/
static void rs485_init(void)
{
    gpio_init_type gpioInitStruct = 
    {
        .gpio_pins           = RS485_DE_RE_GPIO_PIN,
        .gpio_out_type       = GPIO_OUTPUT_PUSH_PULL,
        .gpio_pull           = GPIO_PULL_NONE,
        .gpio_mode           = GPIO_MODE_OUTPUT,
        .gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER,
    };
    
    //RS485 GPIO初始化
    crm_periph_clock_enable(RS485_GPIO_CRM, TRUE);
    gpio_init(RS485_DE_RE_GPIO_PORT, &gpioInitStruct);
    gpioInitStruct.gpio_mode = GPIO_MODE_MUX;
    gpioInitStruct.gpio_pins = RS485_USART_TX_GPIO_PIN;
    gpio_init(RS485_USART_TX_GPIO_PORT, &gpioInitStruct);
    gpioInitStruct.gpio_pins = RS485_USART_RX_GPIO_PIN;
    gpio_init(RS485_USART_RX_GPIO_PORT, &gpioInitStruct);
    gpio_pin_mux_config(RS485_USART_TX_GPIO_PORT, RS485_USART_TX_GPIO_MUX_SOURCE, RS485_USART_TX_GPIO_MUX);
    gpio_pin_mux_config(RS485_USART_RX_GPIO_PORT, RS485_USART_RX_GPIO_MUX_SOURCE, RS485_USART_RX_GPIO_MUX);
    
    //RS485 USART初始化
    crm_periph_clock_enable(RS485_USART_CRM, TRUE);
    usart_parity_selection_config(RS485_USART, RS485_USART_PARITY);
    usart_init(RS485_USART, RS485_USART_BAUDRATE, RS485_USART_DATA, RS485_USART_STOP);
    usart_transmitter_enable(RS485_USART, FALSE);
    usart_receiver_enable(RS485_USART, TRUE);
    usart_flag_clear(RS485_USART, USART_RDBF_FLAG);
    usart_flag_clear(RS485_USART, USART_IDLEF_FLAG);
    usart_interrupt_enable(RS485_USART, USART_RDBF_INT, TRUE);
    usart_interrupt_enable(RS485_USART, USART_IDLE_INT, TRUE);
    usart_enable(RS485_USART, FALSE);
    
    //RS485 NVIC初始化
    nvic_irq_enable(RS485_USART_IRQ, 0, 0);
}


/**
 * @brief   RS485配置
 * @param   None
 * @retval  None
 * @note    None
*/
void rs485_config(void)
{
    rs485_init();
    
    rs485Mode = RS485_MODE;
    rs485Id = RS485_ID;
    rs485UsartBaudRate = RS485_USART_BAUDRATE;
    rs485ActiveInterval = RS485_ACTIVE_INTERVAL;
    
    RS485_MODE_RX;
}
